#include <stdio.h>
#include <errno.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>

static int g_pipe_fd[2] = {0};

#define COMMON1 1

static int handle_command(int cmd)
{
//	debug(1, "ipc receive command:%s\n", command_string[cmd]);
	switch(cmd) {
		case COMMON1:
			printf("common 1\n");
			break;
		default:
			fprintf(stderr, "unhandled cmd:%d\n", cmd);
			break;
	}
	return 0;
}

int handle_func()
{    
		char buf[5];
		while(1) {
			if (read(g_pipe_fd[0], buf, 1) < 0) {
				fprintf(stderr, "read pipe failed:%s\n", strerror(errno) );
				return -1;
			}
			handle_command((int)buf[0]);
		}
}


void* send_func(void *args)
{    
    pthread_detach(pthread_self());
		char msg_recv[5] = {0};
		msg_recv[0] = COMMON1; 
		int byte;
		while(1) {
			if ( (byte = write(g_pipe_fd[1], &msg_recv, 1)) == -1) {
	        fprintf(stderr, "write failed! %s\n", strerror(errno) );
	        return NULL;
	    }
			sleep(5);
		}
}

int create_send_func()
{
	static pthread_t tid = 0;
	if ( (pthread_create(&tid, NULL, send_func, NULL)) != 0) {
			printf("create_ipcserver_thread error!\n");
			return -1;
	}
	return 0;
}

int main()
{
	if(pipe(g_pipe_fd)) {
	    fprintf(stderr, "pipe failed! %s\n", strerror(errno) );
	    return -1;
	}
  if (create_send_func() < 0)
  	return -1;
	handle_func();
	return 0;
}